package frontend;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import logs.LogFactory;

import org.apache.log4j.Logger;

import backend.db.ORM;

/**
 * Servlet implementation class MyCourses
 */
public class MyCourses extends HttpServlet {
  private static final Logger logger = LogFactory.getLog(MyCourses.class);
  private static final long serialVersionUID = 1L;
  
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) {
    logger.debug("MyCourses");
    final String username = request.getParameter("username");
    String course = request.getParameter("course");
    try {
      if (course != null)
        ORM.removeCourseFromUser(username, course);
      else {
        final int length = Integer.parseInt(request.getParameter("selLength"));
        for (int i = 0; i < length; i++) {
          course = request.getParameter("course" + i);
          ORM.removeCourseFromUser(username, course);
        }
      }
    } catch (final NumberFormatException e) {
      try {
        logger.warn("parameter problem in MyCourses", e);
        response.sendError(HttpStatus.SC_BAD_REQUEST);
      } catch (final IOException e1) {
        logger.error("error sending an error", e1);
      }
    }
    logger.debug("MyCourses ended");
  }
}
